/*
 * @Author: NtyAaron
 * @Date: 2021-04-12 11:13:45
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-06-30 18:13:53
 * @Description: 大湾区概览
 * @FilePath: \dwq\pages\overview\overview.js
 */

const app = getApp()
import { getCityList, getAllIndustry, getCategoryList, getArticlePage } from '../../api/article/article'
import { saveCollect, delCollect } from '../../api/article/article'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
import { _t } from '../../i18n/base'
import { getPosterList } from '../.../../../api/advert/advert'

Page({
  data: {
    // 文章分类
    categoryList: [],
    // 行业列表
    industryList: [],
    // 城市列表
    cityList: [],
    // 文章列表
    momentList: [],
    industry: '行业',
    city: '地区',
    categorySwitch: 0,
    categoryTitle: '',
    categoryId: '',
    citySwitch: 1,
    cityId: 0,
    mainActiveIndex: 0,
    val: '',
    activeId: [],
    articleReqEvent: {
      categoryId: '',
      categoryType: 1,
      cityId: '',
      industryId: '',
      language: 1,
      title: '',
      userId: '',
      page: 1,
      size: 20,
    },
    totalCount: 0,
    pageLoading: false,
    collectStatus: 0,
    messagePath: '/pages/overview/overview',
    messageImg: '/images/logo新.png',
    getAdvertObj: {
      categoryType: 1,
      language: '',
      posterName: '',
      posterType: 4,
      showType: 1,
      trafficType: '',
    },
    bannerList: [],
    showTips: false,
    cateSelectList: [],
    citySelectList: [],
    industrySelectList: [],
  },
  // 监听搜索
  onSearch({ detail }) {
    this.setData({
      ['articleReqEvent.title']: detail,
    })
    this.getArticlePage(this.data.articleReqEvent)
  },
  // 分类点击
  categorySelectHandle({ detail }) {
    let { cateSelectList } = this.data
    const index = cateSelectList.indexOf(detail)
    if (index > -1) {
      cateSelectList.splice(index, 1)
    } else {
      cateSelectList.push(detail)
    }
    let list = []
    cateSelectList.map((item) => {
      list.push(this.data.categoryList[item].categoryId)
    })
    this.setData({
      ['articleReqEvent.categoryId']: list.indexOf(65) != -1 ? 0 : JSON.stringify(list).replace(/\[|]/g, ''),
      categoryTitle: this.data.categoryList[detail].categoryName,
      cateSelectList,
    })
    this.getArticlePage(this.data.articleReqEvent)
    if (cateSelectList.length == 0) {
      this.setData({
        categoryTitle: this.data.cateSeatTitle,
      })
    }
  },
  // 点击行业一级列表
  onClickNav({ detail }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    })
  },
  // 点击行业二级列表
  onClickItem({ detail }) {
    const { industrySelectList } = this.data
    const index = industrySelectList.indexOf(detail.id)
    if (index > -1) {
      industrySelectList.splice(index, 1)
    } else {
      industrySelectList.push(detail.id)
    }
    this.setData({
      industrySelectList,
      industryTitle: detail.text,
      ['articleReqEvent.industryId']: industrySelectList.indexOf(0) != -1 ? 0 : JSON.stringify(industrySelectList).replace(/\[|]/g, ''),
    })
    this.getArticlePage(this.data.articleReqEvent)
    if (industrySelectList.length == 0) {
      this.setData({
        industryTitle: this.data.lang['行业'],
      })
    }
  },
  // 点击地区
  citySelectHandle({ detail }) {
    let { citySelectList } = this.data
    const index = citySelectList.indexOf(detail)
    if (index > -1) {
      citySelectList.splice(index, 1)
    } else {
      citySelectList.push(detail)
    }
    let list = []
    citySelectList.map((item) => {
      list.push(this.data.cityList[item].cityId)
    })
    this.setData({
      ['articleReqEvent.cityId']: list.indexOf(0) != -1 ? 0 : JSON.stringify(list).replace(/\[|]/g, ''),
      citySwitch: JSON.stringify(list).replace(/\[|]/g, ''),
      city: this.data.cityList[detail].text,
      citySelectList,
    })
    this.getArticlePage(this.data.articleReqEvent)
    if (citySelectList.length == 0) {
      this.setData({
        city: this.data.lang['地区'],
      })
    }
  },
  // 获取文章列表
  async getArticlePage(e) {
    this.getPosterList()
    this.setData({
      ['articleReqEvent.page']: 1,
    })
    let { result } = await getArticlePage(e)
    if (result.content.length != 0) {
      let afterChangeResult = result.content.map((item) => {
        if (item.publishTime != null) {
          item.publishTime = item.publishTime.split(' 00:00:00')[0]
        }
        return item
      })
      this.setData({
        totalCount: result.totalCount,
        momentList: afterChangeResult,
        showTips: false,
      })
    } else {
      this.setData({
        momentList: [],
        showTips: true,
      })
    }
  },
  // 滑动底部
  async scrollEnd() {
    if (this.data.momentList.length < this.data.totalCount) {
      this.setData({
        ['articleReqEvent.page']: this.data.articleReqEvent.page + 1,
      })
      let { result } = await getArticlePage(this.data.articleReqEvent)
      if (result.content.length != 0) {
        let afterChangeResult = result.content.map((item) => {
          if (item.publishTime != null) {
            item.publishTime = item.publishTime.split(' 00:00:00')[0]
          }
          return item
        })
        this.setData({
          totalCount: result.totalCount,
          momentList: this.data.momentList.concat(afterChangeResult),
        })
      }
    } else {
      wx.showToast({
        title: this.data.lang['没有更多数据了'],
      })
    }
  },
  // 获取城市列表
  async getCityList() {
    let { result } = await getCityList(wx.getStorageSync('lang'))
    var i = 1
    result.map((item) => {
      item.text = item.cityName
      item.cityId = item.cityId
      item.value = i
      i++
    })
    let arr = [{ text: this.data.lang['全大湾区'], value: 0, cityId: 0 }]
    result = arr.concat(result)
    this.setData({
      cityList: result,
    })
  },
  // 获取一级二级行业列表
  async getAllIndustryList() {
    let { result } = await getAllIndustry(wx.getStorageSync('lang'))
    var res = [
      {
        id: 0,
        text: this.data.lang['全部行业'],
        children: [
          {
            id: 0,
            text: this.data.lang['全部'],
          },
        ],
      },
    ]
    this.setData({
      industryList: res.concat(result),
    })
  },
  // 获取第一个分类下拉菜单
  async getCategoryList() {
    let { result } = await getCategoryList({
      type: 1,
      language: wx.getStorageSync('lang'),
    })
    let idx = 0
    result.map((item) => {
      item.text = item.categoryName
      item.value = idx++
      item.categoryId = item.categoryId
    })
    this.setData({
      categoryList: result,
      categoryTitle: result[0].categoryName,
      cateSeatTitle: result[0].categoryName,
    })
  },
  // 点击列表进入文章详情
  toMomentDetailHandle({ detail }) {
    let vantObj = {
      type: detail.type,
      id: detail.momentId,
      title: detail.title,
      language: this.data.language,
    }
    this.vantDialog(vantObj)
  },
  // 点击广告进入客服
  adClickHandle({ detail }) {
    let vantObj = {
      type: detail.type,
      id: detail.posterId,
      title: detail.posterName,
      language: this.data.language,
    }
    this.vantDialog(vantObj)
  },
  //vant 弹窗组件（用于进入客服）
  vantDialog(e) {
    Dialog.confirm({
      title: this.data.lang['查看内容'],
      message: this.data.lang['跳转内容链接'],
      confirmButtonText: this.data.lang['确定'],
      cancelButtonText: this.data.lang['取消'],
      confirmButtonOpenType: 'contact',
      sendMessageTitle: e.title,
      sendMessagePath: `${this.data.messagePath}?${e.id},${e.type}`,
      sendMessageImg: this.data.messageImg,
      showMessageCard: true,
    })
      .then(async () => {
        setTimeout(() => {
          console.log(12)
        })
      })
      .catch(() => {})
  },
  // 点击收藏
  async toCollectHandle({ detail }) {
    this.setData({
      ['articleReqEvent.articleId']: detail.momentId,
    })
    if (detail.collect == 1) {
      //取消收藏
      let { result } = await delCollect({ ids: detail.collectId })
      if (result) {
        this.getArticlePage(this.data.articleReqEvent)
      }
    } else {
      if (wx.getStorageSync('userId')) {
        let { result } = await saveCollect(this.data.articleReqEvent)
        if (result) {
          this.setData({
            collectStatus: result.status,
          })
          this.getArticlePage(this.data.articleReqEvent)
        }
      } else {
        wx.reLaunch({
          url: '/pages/index/index',
        })
      }
    }
  },
  // 点击转发
  toForwardHandle({ detail }) {
    wx.setClipboardData({
      data: detail,
      success: () => {
        wx.showToast({
          title: this.data.lang['已复制网站网址'],
          icon: 'none',
        })
      },
    })
  },
  // 获取本地用户信息
  initLocaStayInfo() {
    let userId = wx.getStorageSync('userId')
    if (userId) {
      this.setData({
        ['articleReqEvent.userId']: userId,
      })
    }
  },
  // 获取广告
  async getPosterList() {
    this.setData({
      'getAdvertObj.language': wx.getStorageSync('lang'),
    })
    let { result } = await getPosterList(this.data.getAdvertObj)
    if (result) {
      result.map((item) => {
        item.bannerLink = `${app.globalData.host}/attach/showPic?attachId=${item.pic}`
      })
      this.setData({
        bannerList: result,
      })
    }
  },
  // 删除搜索关键词
  onCancel() {
    this.setData({
      ['articleReqEvent.title']: '',
    })
    this.getArticlePage(this.data.articleReqEvent)
  },
  onShow() {
    this.initLocaStayInfo()
  },
  // 初始化
  onLoad() {
    const langData = _t()
    let lang = wx.getStorageSync('lang')
    this.setData({
      ['articleReqEvent.language']: lang,
      lang: langData,
      industryTitle: langData['行业'],
      city: langData['地区'],
      language: lang,
    })
    wx.setNavigationBarTitle({
      title: langData['大湾区概览'],
    })
    this.getArticlePage(this.data.articleReqEvent)
    this.initLocaStayInfo()
    this.getCategoryList()
    this.getCityList()
    this.getAllIndustryList()
  },
})
